package com.demo;

import fun.carliels.doraemon.doc.excel.ExcelReader;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.List;

/**
 * 山冶院商品导入数据，商品属性页，行转列
 */
public class RmsProductMallWareImport {

    public static void main(String[] args) throws FileNotFoundException {
        String originalFile = "D:\\tmp\\rms_mall_wares\\标准样品-钢铁-光谱.xlsx";
        String targetFile = "D:\\tmp\\rms_mall_wares\\标准样品-钢铁-光谱.csv";
        List<WareProp> wareProps = readFromExcel(originalFile);
        if (CollectionUtils.isNotEmpty(wareProps)) {
            writeCsv(targetFile, wareProps);
        }
    }

    /**
     * 读取文件内容并格式化
     * @param fileUrl
     * @return
     */
    public static List<WareProp> readFromExcel(String fileUrl) {
        List<WareProp> result = new ArrayList<>();
        List<String> originals = ExcelReader.readExcel(fileUrl, (cols, titles) -> {
            String code = ExcelReader.getColValue(cols, 0);
            for (int i = 1; i < titles.size(); i++) {
                String pVal = ExcelReader.getColValue(cols, i);
                if (StringUtils.isNotBlank(pVal)) {
                    result.add(new WareProp(code, titles.get(i), pVal));
                }
            }
            return code;
        });
        return result;
    }

    /**
     * 写出csv文件
     * @param fileUrl
     * @param props
     * @throws FileNotFoundException
     */
    public static void writeCsv(String fileUrl, List<WareProp> props) throws FileNotFoundException {
        props.add(0, new WareProp("商品编码", "商品属性", "商品属性值"));
        File csvOutputFile = new File(fileUrl);
        try (PrintWriter pw = new PrintWriter(csvOutputFile)) {
            props.stream()
                    .map(x -> {
                        return String.format("%s,%s,%s", x.getCode(), x.getPropName(), x.getPropVal());
                    })
                    .forEach(pw::println);
        }
    }
}
